// 配置marked
marked.setOptions({
    highlight: function(code, lang) {
        if (lang && hljs.getLanguage(lang)) {
            try {
                return hljs.highlight(code, { language: lang }).value;
            } catch (err) {
                console.error('代码高亮失败:', err);
            }
        }
        try {
            return hljs.highlightAuto(code).value;
        } catch (err) {
            console.error('代码高亮失败:', err);
            return code;
        }
    },
    breaks: true,
    gfm: true,
    headerIds: false,
    mangle: false
});

// 获取URL参数
function getUrlParam(name) {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get(name);
}

// 格式化日期
function formatDate(date) {
    return new Date(date).toLocaleString();
}

// 加载文章详情
async function loadArticle() {
    const articleId = getUrlParam('id');
    if (!articleId) {
        layer.msg('文章ID不能为空');
        window.location.href = '/';
        return;
    }

    try {
        const res = await axios.get(`/api/articles/${articleId}`);
        if (res.data.code === 200) {
            const article = res.data.data;
            const elements = {
                title: document.getElementById('title'),
                author: document.getElementById('author'),
                createTime: document.getElementById('createTime'),
                category: document.getElementById('category'),
                tags: document.getElementById('tags'),
                viewCount: document.getElementById('viewCount'),
                likeCount: document.getElementById('likeCount'),
                content: document.getElementById('content')
            };

            // 检查所有必需的元素是否存在
            for (const [key, element] of Object.entries(elements)) {
                if (!element) {
                    console.error(`元素 ${key} 不存在`);
                    return;
                }
            }

            // 更新文章内容
            elements.title.textContent = article.title;
            elements.author.textContent = `作者：${article.author || ''}`;
            elements.createTime.textContent = `发布时间：${formatDate(article.createTime)}`;
            elements.category.textContent = article.category ? `分类：${article.category.name}` : '';
            elements.tags.textContent = article.tags && article.tags.length > 0
                ? `标签：${article.tags.map(tag => tag.name).join('、')}`
                : '';
            elements.viewCount.textContent = `阅读：${article.viewCount}`;
            elements.likeCount.textContent = `喜欢：${article.likeCount}`;
            
            // 使用marked解析Markdown内容
            const content = article.content || '';
            elements.content.innerHTML = marked.parse(content);
            
            // 加载评论列表
            loadComments(articleId);
        }
    } catch (error) {
        console.error('加载文章失败:', error);
        layer.msg('加载文章失败');
    }
}

// 加载评论列表
async function loadComments(articleId) {
    try {
        const res = await axios.get('/api/comments/list', {
            params: { articleId: articleId }
        });
        if (res.data.code === 200) {
            const comments = res.data.data.records || [];
            const commentList = document.getElementById('commentList');
            const template = document.getElementById('commentTemplate');
            
            if (!commentList || !template) {
                console.error('评论列表或模板元素不存在');
                return;
            }
            
            // 清空评论列表
            commentList.innerHTML = '';
            
            if (comments.length === 0) {
                commentList.innerHTML = '<div class="no-comments">暂无评论</div>';
                return;
            }
            
            // 添加评论
            comments.forEach(comment => {
                const clone = template.content.cloneNode(true);
                clone.querySelector('.comment-author').textContent = comment.author;
                clone.querySelector('.comment-time').textContent = formatDate(comment.createTime);
                clone.querySelector('.comment-content').textContent = comment.content;
                commentList.appendChild(clone);
            });
        }
    } catch (error) {
        console.error('加载评论失败:', error);
        layer.msg('加载评论失败');
    }
}

// 提交评论
async function submitComment() {
    const articleId = getUrlParam('id');
    const commentContent = document.getElementById('commentContent');
    
    if (!commentContent) {
        console.error('评论输入框不存在');
        return;
    }
    
    const content = commentContent.value.trim();
    if (!content) {
        layer.msg('请输入评论内容');
        return;
    }

    const token = localStorage.getItem('token');
    if (!token) {
        layer.msg('请先登录后再评论');
        return;
    }
    
    try {
        const res = await axios.post('/api/comments', {
            articleId: articleId,
            content: content
        });
        
        if (res.data.code === 200) {
            layer.msg('评论成功');
            commentContent.value = '';
            loadComments(articleId);
        } else {
            layer.msg(res.data.message || '评论失败');
        }
    } catch (error) {
        console.error('评论失败:', error);
        layer.msg('评论失败');
    }
}

// 检查登录状态
async function checkLogin() {
    const token = localStorage.getItem('token');
    if (token) {
        try {
            const res = await axios.get('/api/users/current', {
                headers: { 'Authorization': token }
            });
            if (res.data.code === 200) {
                document.getElementById('username').textContent = res.data.data.username;
                document.getElementById('logout').style.display = 'inline';
                document.getElementById('login').style.display = 'none';
                document.getElementById('register').style.display = 'none';
                return true;
            } else {
                localStorage.removeItem('token');
                showLoginButtons();
                return false;
            }
        } catch (error) {
            console.error('获取用户信息失败:', error);
            localStorage.removeItem('token');
            showLoginButtons();
            return false;
        }
    } else {
        showLoginButtons();
        return false;
    }
}

// 显示登录按钮
function showLoginButtons() {
    document.getElementById('username').textContent = '';
    document.getElementById('logout').style.display = 'none';
    document.getElementById('login').style.display = 'inline';
    document.getElementById('register').style.display = 'inline';
}

// 检查点赞状态
async function checkLikeStatus() {
    const articleId = getUrlParam('id');
    const likeBtn = document.getElementById('likeBtn');
    if (!likeBtn) {
        console.error('点赞按钮不存在');
        return;
    }
    
    try {
        const res = await axios.get(`/api/likes/articles/${articleId}`);
        if (res.data.code === 200) {
            const isLiked = res.data.data;
            likeBtn.textContent = isLiked ? '取消喜欢' : '喜欢';
            likeBtn.classList.toggle('liked', isLiked);
        }
    } catch (error) {
        console.error('获取点赞状态失败:', error);
    }
}

// 处理点赞
async function handleLike() {
    const articleId = getUrlParam('id');
    const token = localStorage.getItem('token');
    if (!token) {
        layer.msg('请先登录后再点赞');
        return;
    }
    
    const likeBtn = document.getElementById('likeBtn');
    if (!likeBtn) {
        console.error('点赞按钮不存在');
        return;
    }
    
    try {
        const isLiked = likeBtn.classList.contains('liked');
        const url = isLiked ? 
            `/api/likes/articles/${articleId}/cancel` : 
            `/api/likes/articles/${articleId}`;
            
        const res = await axios.post(url);
        if (res.data.code === 200) {
            likeBtn.textContent = isLiked ? '喜欢' : '取消喜欢';
            likeBtn.classList.toggle('liked');
            const likeCount = document.getElementById('likeCount');
            if (likeCount) {
                const currentCount = parseInt(likeCount.textContent.split('：')[1]);
                likeCount.textContent = `喜欢：${isLiked ? currentCount - 1 : currentCount + 1}`;
            }
            layer.msg(isLiked ? '取消点赞成功' : '点赞成功');
        }
    } catch (error) {
        console.error('点赞失败:', error);
        layer.msg('点赞失败');
    }
}

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', async function() {
    try {
        // 加载文章
        await loadArticle();
        
        // 检查登录状态
        const isLoggedIn = await checkLogin();
        if (isLoggedIn) {
            // 如果已登录，检查点赞状态
            await checkLikeStatus();
        }
        
        // 绑定事件
        const submitCommentBtn = document.getElementById('submitComment');
        const likeBtn = document.getElementById('likeBtn');
        
        if (submitCommentBtn) {
            submitCommentBtn.addEventListener('click', submitComment);
        }
        
        if (likeBtn) {
            likeBtn.addEventListener('click', handleLike);
        }
    } catch (error) {
        console.error('页面初始化失败:', error);
        layer.msg('页面加载失败');
    }
});

// 在页面加载时，检查登录状态
axios.get('/api/users/current').then(res => {
    if (!res.data) {
        window.location.href = 'login.html';
    }
}).catch(() => {
    window.location.href = 'login.html';
}); 